<?php

namespace App\Admin\Controllers;

use App\Models\City;
use App\Models\Member\Member;
use App\Models\Nation;
use App\Models\Obj;
use App\Models\Org;
use EasyWeChat\Factory;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Encore\Admin\Grid\Displayers\Actions;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use GuzzleHttp\Client; // 假设使用GuzzleHttp作为HTTP客户端
use GuzzleHttp\RequestOptions;




class ObjController extends AdminController
{
    protected $title = '帮扶对象管理';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Obj());

        $grid->title('用户姓名')->style('min-width:100px;');
        $grid->column('nation.nation', '民族')->label('info')->style('min-width:100px;');
        $grid->home_num('家庭人数')->style('min-width:100px;');
        $grid->phone('联系方式')->style('min-width:100px;');
        $grid->source('收入来源')->style('min-width:100px;');
        // 不存在的`full_name`字段
        $grid->column('all_address', '地址')->display(function () {
            return  $this->city->name.' '. $this->county->name.' '. $this->address;
        })->style('min-width:150px;');
//        $grid->column('province.name', '省');
//        $grid->column('city.name', '市');
//        $grid->column('county.name', '区/县');
//        $grid->address('地址');
//        $grid->column('erweima')->carousel(300, 300, env('APP_URL'));

//        $grid->column('erweima', '二维码')->qrcode()->style('min-width:150px;');
        $grid->column('erweima', '二维码')->downloadable()->style('min-width:150px;');
//        $grid->column('erweima', '二维码')->style('min-width:150px;')->lightbox(['width' => 100, 'height' => 100])->zoom();
        // $grid->column('erweima', '二维码')->image(env('APP_URL'), 200, 200)->zoom();
        $grid->column('status', '状态')->using(['0' => '禁用', '1' => '启用'], '未知')->dot([
            0 => 'danger',
            1 => 'success',
        ], 'warning')->sortable()->style('min-width:100px;');

//        $grid->column('created_at', '创建时间')->sortable();

        $grid->disableExport();
        $grid->disableRowSelector();

        $grid->actions(function ($actions) {
            // 去掉查看
            $actions->disableView();
        });

        $grid->filter(function (Grid\Filter $filter) {
            $filter->expand();
            // 去掉默认的id过滤器
            $filter->disableIdFilter();

            $filter->like('title', '用户姓名');
        });

        $grid->setActionClass(Actions::class);

        return $grid;
    }

    protected function detail($id)
    {
        $show = new Show(Obj::findOrFail($id));

        $show->field('title', '用户姓名');
        $show->field('nation.nation', '民族');
        $show->field('home_num', '家庭人数');
        $show->field('source', '收入来源');
        $show->field('city.name', '市');
        $show->field('county.name', '区/县');
        $show->field('address', '地址');
        $show->field('coordinate', '坐标');

        $show->field('坐标')->latlong('lat', 'lng', $height = 500, $zoom = 16);

        $show->field('status', '状态');

        return $show;
    }


    public function cities(Request $request)
    {
        $city_id = $request->get('q');

        return City::where('parent_id', $city_id)->get(['id', DB::raw('name as text')]);
    }

// 获取Access Token
    public function getAccessToken()
    {
        $appId = config('wechat.mini_program.default.app_id'); // 小程序AppID
        $appSecret = config('wechat.mini_program.default.secret'); // 小程序AppSecret
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}";
        $client = new Client();
        $response = $client->request('GET', $url);
        $body = json_decode($response->getBody()->getContents(), true);
        return $body['access_token'];
    }
    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Obj());

        $form->display('id', 'ID');

        $form->text('title', '姓名')->rules('required');
        $form->select('nation_id', '民族')->options(Nation::all()->pluck('nation', 'id'));
        $form->number('home_num', '家庭人数')->rules('required');
        $form->text('phone', '联系方式')->rules('required');
        $form->text('source', '收入来源');

        $form->select('city_id', '市')->options(City::where('type', 'city')->pluck('name', 'id'))->load('county_id', 'api/cities')->rules('required');


        $form->select('county_id', '区/县')->options(function ($id) {
            return City::where('type', 'area')->where('id', $id)->pluck('name', 'id');
        })->rules('required');

        $form->text('address', '详细地址')->rules('required');

        $form->latlong('lat', 'lng', '坐标')->width(800)->height(500)->zoom(16)->default(['lat' => 29.237608178971893, 'lng' => 91.76899932324886]);


//        $form->text('coordinate', '坐标')->rules('required')->help('请通过网址：https://lbs.qq.com/getPoint/ 去获取坐标');

        $form->radio('status', '状态')->options(['0' => '禁用', '1' => '启用'])->default('1');

        $form->saved(function (Form $form) {

            Obj::where('id', $form->model()->id)->update([
                'org_id' => Admin::user()->org_id,
            ]);

            if(!file_exists(public_path('erweima/' . $form->model()->id . '.png'))){

                $access_token = $this->getAccessToken();
                $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$access_token}";
                $data = [
                    'scene' => 'id='.$form->model()->id, // 场景值，最大32个字符
                    'page' => 'pages/helprecord/helprecord', // 小程序页面路径
                    'width' => 430, // 二维码的宽度
                ];

                $client = new Client();
                $response = $client->request('POST', $url, [
                    RequestOptions::JSON => $data, // 发送JSON数据
                    RequestOptions::HEADERS => [
                        'Content-Type' => 'application/json' // 设置请求头
                    ]
                ]);

                // 假设响应体是图片的二进制数据
                $imageContent = (string)$response->getBody();
//
                // 保存到文件示例
                file_put_contents(public_path('erweima/' . $form->model()->id . '.png'), $imageContent);

                Obj::where('id', $form->model()->id)->update([
                    'erweima' => env('APP_URL').'erweima/' .$form->model()->id.'.png',
                ]);


            }
        });

        $form->footer(function ($footer) {
            // 去掉`查看`checkbox
            $footer->disableViewCheck();
            // 去掉`继续编辑`checkbox
            $footer->disableEditingCheck();
            // 去掉`继续创建`checkbox
            $footer->disableCreatingCheck();

        });

        $form->tools(function (Form\Tools $tools) {
            // 去掉`列表`按钮
            $tools->disableList();
            // 去掉`删除`按钮
            $tools->disableDelete();
            // 去掉`查看`按钮
            $tools->disableView();
        });

        return $form;
    }
}
